/* ReMeMore-Moi
 * Code license: Apache License 2.0
 * WWW : http://code.google.com/p/rememore-moi/
 * */
package info.fredericb.rememoremoi;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;

public class PhoneIntentReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			String state = bundle.getString("state");
			if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
				String phoneNumber = intent.getExtras().getString("incoming_number");
				ContactAccessor contactAccessor = ContactAccessor.getInstance();
				// API Level 5 minimum
				//Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
				//ContentResolver resolver = context.getContentResolver();
				//Cursor cur = context.getContentResolver().query(uri, new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null);
				
				ContentResolver resolver = context.getContentResolver();
				String name = contactAccessor.findPhoneNumber(resolver, phoneNumber);
				if(name == null){
					intent.setClass(context, RememoremoiService.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					Log.d("DEBUG",intent.toString());
					context.startService(intent);
				}
				
//				Uri contactUri = Uri.withAppendedPath(Contacts.Phones.CONTENT_FILTER_URL, Uri.encode(phoneNumber));
//				Cursor cur = context.getContentResolver().query(contactUri, new String [] {Contacts.People.NAME}, null, null, null);
//				if(cur != null){
//					int i = cur.getCount();
//					if(i == 0){
//						intent.setClass(context, RememoremoiService.class);
//						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						context.startService(intent);
//					}
//				}
			}
		}
	}
}
